import { cloneDeep } from 'lodash-es';
import { EVENTS, type IEventBus } from '../../events';
import { BaseModel } from '../base';
import { MODEL_NAME } from '../../constants/model-names';
import { FEATURE_UNLOCK_DATA } from '../../data/feature-unlock';
import type {
  FeatureUnlockConfig,
  FeatureId,
} from '../../data/feature-unlock/type';

export class FeatureUnlockModel extends BaseModel {
  public name = MODEL_NAME.FEATURE_UNLOCK;
  private bus: IEventBus;

  private unlockMap: Map<FeatureId, boolean> = new Map();
  private conditions: FeatureUnlockConfig[] = cloneDeep(FEATURE_UNLOCK_DATA);

  constructor(bus: IEventBus) {
    super();
    this.bus = bus;
    this.conditions.forEach((c) => {
      this.unlockMap.set(c.id, false);
    });
  }

  public setUnlock(featureId: FeatureId): void {
    this.unlockMap.set(featureId, true);
    this.bus.emit(EVENTS.FEATURE_UNLOCK_STATE_UPDATE);
  }

  public isUnlocked(featureId: FeatureId): boolean {
    return this.unlockMap.get(featureId) || false;
  }

  public getConditions() {
    return this.conditions;
  }

  public getUnlockedFeatures(): FeatureId[] {
    return Array.from(this.unlockMap.keys()).filter((k) =>
      this.unlockMap.get(k)
    );
  }

  public get uiState() {
    return {
      unlockedFeatures: this.getUnlockedFeatures(),
    };
  }
}
